<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2019/1/22
 * Time: 12:15 PM
 */

namespace api\models;


use api\models\JobInfo;
use common\models\Mission;
use common\models\Order;

/**
 * This is the model class for table "job".
 *
 */

class Job extends \common\models\Job
{
    private $_info;

    public $date;

    public function fields()
    {
        return [
            'uid',
            'type',
            'pay_needed',
            'created_at',
            'updated_at',
            'contact_name',
            'contact_phone',
            'title',
            'content',
            'detail'=>function($model){
                /**@var Job $model*/
               return $model->jobInfo;
            }

        ];
    }


    public function getInfo(){
        return $this->_info;
    }

    public function setInfo($date){
        $this->_info = $date;
    }

    public function getJobInfo(){
        return self::hasOne(JobInfo::className(),['jid' => 'id']);
    }

    public function beforeValidate()
    {
        $this->uid = \Yii::$app->user->id;
        return parent::beforeValidate();
    }


    public function beforeSave($insert)
    {
        $this->date = \Yii::$app->getRequest()->getBodyParams();
        $this->uid = \Yii::$app->user->id;
        if ($insert){
            $this->created_at = $this->updated_at  = time();
            if (isset($this->info->good_id) && $this->info->good->price > 0) {
                $this->pay_needed = self::PAY_NEEDED;
            } else {
                $this->pay_needed = self::PAY_NOT_NEEDED;
            }

        }else{
            $this->updated_at = time();
        }

        //TODO:在保存之前做是否可以付款的检测而非在储存之后



        return parent::beforeSave($insert);
    }


    public function afterSave($insert, $changedAttributes)
    {
        if (JobInfo::findOne(['jid'=>$this->id])){
            $this->info = $this->getJobInfo();
            $this->info->load($this->date,'');
        }else{
            $this->info = new JobInfo();
            $this->info->load($this->date,'');
        }
        $this->info->jid = $this->id;
        $this->info->save();
        //重复代码
        if ($insert) {
            if (isset($this->info->good_id) && $this->info->good->price > 0) {
                $this->pay_needed = self::PAY_NEEDED;
            } else {
                $this->pay_needed = self::PAY_NOT_NEEDED;
            }
        }
        parent::afterSave($insert, $changedAttributes);
    }


    public static function signUpCharge($jid, Order $order)
    {
        $job = Job::findOne($jid);
        if ($job != null) {
            //根据订单的购买数量增加
            $job->view_num = $job->view_num < 5 ? 5 : $job->view_num;
            $job->view_num += ! empty($order->number) ? $order->number : 1;

            return $job->save();
        }

        return false;
    }



}